package com.ruoyi.config.emqx;


import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EmqxApiClient {
    private String baseUrl;
    private HttpClient client;
    private final String apiKey;
    private final String apiSecret;

    public EmqxApiClient(@Value("${emqx.host}") String host,
                         @Value("${emqx.port}") int port,
                         @Value("${emqx.api-key}") String apiKey,
                         @Value("${emqx.api-secret}") String apiSecret) {
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        this.baseUrl = String.format("http://%s:%d/api/v5", host, port);
        this.client = HttpClient.newBuilder().build();
    }

    // 获取所有在线客户端
    public JSONArray getOnlineClients() throws Exception {
        String authHeader = "Basic " + Base64.getEncoder().encodeToString(
                (apiKey + ":" + apiSecret).getBytes(StandardCharsets.UTF_8));
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/clients"))
                .header("Authorization", authHeader)
                .GET()
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == 200) {
            JSONObject result = JSONObject.parseObject(response.body());
            return result.getJSONArray("data");
        } else {
            throw new Exception("Failed to get clients: " + response.body());
        }
    }

    // 获取指定客户端详情
    public JSONObject getClientDetail(String clientId) throws Exception {
        String authHeader = "Basic " + Base64.getEncoder().encodeToString(
                (apiKey + ":" + apiSecret).getBytes(StandardCharsets.UTF_8));
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/clients/" + clientId))
                .header("Authorization", authHeader)
                .GET()
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == 200) {
            return JSONObject.parseObject(response.body());
        } else {
            throw new Exception("Failed to get client detail: " + response.body());
        }
    }
}
